package com.fattyCorps.config;

import com.fattyCorps.cache.PlayerCache;
import com.fattyCorps.exception.CustomBaseException;
import com.fattyCorps.obj.msg.HttpStatus;
import com.fattyCorps.obj.msg.SRet;
import com.fattyCorps.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

@ControllerAdvice
@ResponseBody
@Slf4j
public class CustomExceptionHandler {

    @Autowired
    PlayerCache playerCache;

    //    @ExceptionHandler(CustomBaseException.class)
    @ExceptionHandler(Exception.class)
    public SRet handleHttpMessageNotReadableException(HttpServletRequest request, Exception ex) {
        // 回滚
        Integer playerId = ServletUtils.getPlayerIdByRequest(request, false);
        if (playerId > 0) {
            playerCache.rollback(playerId);
        }

        if (ex instanceof CustomBaseException) {
            // 直接向客户端返回消息
            CustomBaseException cex = (CustomBaseException) ex;
            return SRet.error(cex.getCode(), cex.getMsg());
        }

        log.error(ex.getMessage());
        throw new RuntimeException(ex);
    }
}